import { Divider, Dropdown, Image, Input, List, Space, Tag, Tooltip } from 'antd';
import './style.less'
import { CaretDownOutlined, CloseOutlined, SearchOutlined } from '@ant-design/icons';
import React, { useEffect, useMemo, useState } from 'react';
import { useNodesData, useReactFlow } from '@xyflow/react';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { FIELD_TYPE_MAP } from '@/constant/icons';
import { usePreviousNodes } from '@/hooks/usePreviousNodes';
import { normalizeFieldType, randomUUID } from '@/utils/dataflow';
const svgModules = import.meta.glob('@/assets/image/dataflow/agg/*.svg', { query: '?url', eager: true })

const svgIcons = {};
for (const path in svgModules) {
  const moduleName = path?.split('/')?.pop()?.replace('.svg', '')?.toUpperCase();
  svgIcons[moduleName] = svgModules[path]?.default
}

const FieldList = () => {
  const [searchValue, setSearchValue] = useState(''); // 过滤后的数据
  const currentNode = useCurrentNode()
  const preNode = usePreviousNodes(currentNode?.id)?.[0]
  const preNodeData = useNodesData(preNode?.id)

  const dataSource = preNodeData?.data?.columns

  const searchResult = useMemo(() => {
    if (!searchValue) return dataSource
    return dataSource?.filter(s => s.columnName?.toLowerCase()?.indexOf(searchValue?.toLowerCase()) > -1)
  }, [dataSource, searchValue])

  const handleDrag = (event, data) => {
    event?.dataTransfer?.setData("text/plain", JSON.stringify(data))
  }

  return (
    <div className="field-list-container">
      {/* 搜索框 */}
      <Input
        placeholder="请输入字段名称"
        allowClear
        prefix={<SearchOutlined />}
        onChange={(e) => setSearchValue(e.target.value)} // 实时搜索
        style={{ width: '100%' }}
      />
      {/* 列表 */}
      <div className="field-list">
        <List
          dataSource={searchResult}
          size='small'
          renderItem={(item) => (
            <List.Item style={{ userSelect: 'none', cursor: 'pointer' }}
              draggable onDragStart={(e) => handleDrag(e, item)}>
              <span title={item?.columnComment}>
                <Space>
                  {
                    FIELD_TYPE_MAP[normalizeFieldType(item?.columnType)]?.icon ?? FIELD_TYPE_MAP.unknown.icon
                  }
                  {item?.columnName}
                </Space>
              </span>
            </List.Item>
          )}
        />
      </div>
    </div>
  );
};



const GroupField = () => {
  const currentNode = useCurrentNode();
  const { updateNodeData } = useReactFlow();

  // 使用 useNodesData 监听 currentNode 的 data 变化
  const nodeData = useNodesData(currentNode?.id);
  const groupColumns = nodeData?.data?.groupColumns ?? []
  const allColumns = nodeData?.data?.allColumns ?? []
  const columns = nodeData?.data?.columns ?? []

  // 处理拖拽放置事件
  const handleDrop = (event) => {
    event.preventDefault(); // 必须调用，否则 drop 事件不会触发
    const data = event.dataTransfer.getData('text/plain'); // 获取拖拽的数据
    try {
      const field = JSON.parse(data); // 解析拖拽的数据
      console.log('拖拽的数据:', field);
      if (groupColumns?.some(g => g.columnId === field?.columnId)) return

      // 更新节点的 groupFields，追加新字段
      const updatedGroupFields = [
        ...groupColumns,
        {
          sourceColumnName: field.columnName,
          sourceColumnId: field.columnId,
          sourceColumnType: field.columnType,
          ...field,
        }
      ];
      const updatedAllFields = [
        ...allColumns,
        {
          sourceColumnName: field.columnName,
          sourceColumnId: field.columnId,
          sourceColumnType: field.columnType,
          ...field,
        }
      ]
      updateNodeData(currentNode?.id, { groupColumns: updatedGroupFields, allColumns: updatedAllFields });
    } catch (err) {
      console.error(err)
    }
  }

  // 处理拖拽悬停事件
  const handleDragOver = (event) => {
    event.preventDefault(); // 必须调用，否则 drop 事件不会触发
    event.dataTransfer.dropEffect = 'move'; // 设置拖拽效果
  }

  const handleDelete = (columnId) => {
    const updatedGroupFields = groupColumns?.filter(g => g.columnId !== columnId)
    const updatedAllFields = allColumns?.filter(f => f.columnId !== columnId)
    const updatedFields = columns?.filter(f => f.columnId !== columnId)
    updateNodeData(currentNode?.id, { groupColumns: updatedGroupFields, allColumns: updatedAllFields, columns: updatedFields });
  }

  return (
    <div className='group-field'>
      <div style={{ marginBottom: 20 }}>分组字段</div>
      <div
        className='drop-area'
        onDrop={handleDrop} // 直接传递事件对象
        onDragOver={handleDragOver}
      >
        {groupColumns?.length > 0 ? (
          groupColumns.map((f) => {
            const columnType = normalizeFieldType(f?.sourceColumnType)
            const color = FIELD_TYPE_MAP[columnType]?.presets ?? FIELD_TYPE_MAP.unknown.presets
            const Icon = FIELD_TYPE_MAP[columnType]?.icon ?? FIELD_TYPE_MAP.unknown.icon
            return <Tag key={f.columnId} color={color} style={{ cursor: 'default' }}>
              <span className='tag-content'>
                <Space size={3} className='tag-text'>{Icon}
                  <Tooltip title={f.sourceColumnName} placement='top' mouseLeaveDelay={0}>
                    {f.columnName}
                  </Tooltip>
                </Space>
                <CloseOutlined className='close-icon' onClick={() => handleDelete(f.columnId)} />
              </span>
            </Tag>
          })
        ) : (
          <div className='placeholder'>
            拖拽字段至此处
          </div>
        )}
      </div>
    </div>
  );
};

const menus = [
  {
    key: 'SUM',
    label: '求和',
    belong: ['number'],
    resultType: 'number',
  },
  {
    key: 'AVG',
    label: '取平均值',
    belong: ['number'],
    resultType: 'number'
  },
  {
    key: 'COUNT',
    label: '计数',
    belong: ['number', 'string', 'date'],
    resultType: 'number'
  },
  {
    key: 'DISTINCT',
    label: '去重计数',
    belong: ['number', 'string', 'date'],
    resultType: 'number'
  },
  {
    key: 'MAX',
    label: '最大值',
    belong: ['number', 'date'],
    resultType: 'number'
  },
  {
    key: 'MIN',
    label: '最小值',
    belong: ['number', 'date'],
    resultType: 'number'
  }
]

const aggTypes = menus.reduce((acc, cur) => {
  acc[cur.key] = cur.label
  return acc
}, {})

const SummaryField = () => {
  const currentNode = useCurrentNode();
  const { updateNodeData } = useReactFlow();

  // 使用 useNodesData 监听 currentNode 的 data 变化
  const nodeData = useNodesData(currentNode?.id);
  const aggregatedColumns = nodeData?.data?.aggregatedColumns ?? []
  const allColumns = nodeData?.data?.allColumns ?? []
  const columns = nodeData?.data?.columns ?? []

  // 处理拖拽放置事件
  const handleDrop = (event) => {
    event.preventDefault(); // 必须调用，否则 drop 事件不会触发
    const data = event.dataTransfer.getData('text/plain'); // 获取拖拽的数据
    try {
      const field = JSON.parse(data); // 解析拖拽的数据
      console.log('拖拽的数据:', field);

      // if (aggregatedColumns?.some(g => g.columnName === fields?.columnName)) return

      // 更新节点的 aggregatedColumns
      const aggType = getMenu(field?.columnType).items?.find(item => !item.disabled)
      const newField = {
        sourceColumnName: field.columnName,
        sourceColumnId: field.columnId,
        sourceColumnType: field.columnType,
        columnId: randomUUID(),
        columnType: aggType?.resultType,
        columnName: `(${aggTypes[aggType?.key] || '请选择'})${field.columnName}`,
        aggType: aggType?.key
      }
      const updatedSummaryFields = [
        ...aggregatedColumns,
        {
          ...newField
        }
      ];
      const updatedAllFields = [
        ...allColumns,
        {
          ...newField
        }
      ]
      updateNodeData(currentNode?.id, { aggregatedColumns: updatedSummaryFields, allColumns: updatedAllFields });
    } catch (err) {
      console.error(err)
    }

  }

  // 处理拖拽悬停事件
  const handleDragOver = (event) => {
    event.preventDefault(); // 必须调用，否则 drop 事件不会触发
    event.dataTransfer.dropEffect = 'move'; // 设置拖拽效果
  }

  const handleDelete = (columnId) => {
    const updatedSummaryFields = aggregatedColumns?.filter(s => s.columnId !== columnId)
    const updatedAllFields = allColumns?.filter(a => a.columnId !== columnId)
    const updatedFields = columns?.filter(a => a.columnId !== columnId)
    updateNodeData(currentNode?.id, { aggregatedColumns: updatedSummaryFields, allColumns: updatedAllFields, columns: updatedFields });
  }

  const getMenu = (fieldType, columnId) => {
    const columnType = normalizeFieldType(fieldType)
    const items = menus?.map(menu => {
      return {
        ...menu,
        disabled: !menu.belong.includes(columnType),
        icon: <div><Image src={svgIcons?.[menu?.key]} preview={false} width={18} /></div>,
        onClick: ({ key: aggType }) => {
          const fieldMapper = (field => {
            if (field.columnId === columnId) {
              return {
                ...field,
                aggType,
                columnName: `(${aggTypes[aggType] || '请选择'})${field.sourceColumnName}`
              }
            } else {
              return { ...field }
            }
          })
          const updatedSummaryFields = aggregatedColumns?.map(fieldMapper)
          const updatedAllFields = allColumns?.map(fieldMapper)
          updateNodeData(currentNode?.id, { aggregatedColumns: updatedSummaryFields, allColumns: updatedAllFields });
        }
      }
    })
    return { items }
  }

  return (
    <div className='summary-field'>
      <div style={{ marginBottom: 20 }}>汇总字段</div>
      <div
        className='drop-area'
        onDrop={handleDrop} // 直接传递事件对象
        onDragOver={handleDragOver}
      >
        {aggregatedColumns?.length > 0 ? (
          aggregatedColumns.map((f, idx) => {
            const columnType = normalizeFieldType(f?.sourceColumnType)
            const color = FIELD_TYPE_MAP[columnType]?.presets ?? FIELD_TYPE_MAP.unknown.presets
            const Icon = FIELD_TYPE_MAP[columnType]?.icon ?? FIELD_TYPE_MAP.unknown.icon
            return <Tag key={f.columnId} color={color} style={{ cursor: 'default' }}>
              <span className='tag-content'>
                <Dropdown menu={getMenu(columnType, f.columnId)} trigger='click' placement='top'>
                  <Space size={3} className='tag-text'>{Icon}
                    <Tooltip title={f.sourceColumnName} placement='top' mouseLeaveDelay={0}>
                      <span style={{ fontSize: 13 }}>{f.columnName}</span>
                    </Tooltip>
                  </Space>
                </Dropdown>
                <Space size={1} className='close-icon'>
                  <CaretDownOutlined />
                  <CloseOutlined onClick={() => handleDelete(f.columnId)} />
                </Space>
              </span>
            </Tag>
          })
        ) : (
          <div className='placeholder'>
            拖拽字段至此处
          </div>
        )}
      </div>
    </div>
  );
}

const FieldOperate = () => {
  return <div className='field-operate-container'>
    <GroupField />
    <SummaryField />
  </div>
}

export const Aggregate = () => {
  return (
    <div className='aggregate-container'>
      <FieldList />
      <Divider type='vertical' style={{ height: '100%' }} />
      <FieldOperate />
    </div>
  );
};